// pages/store/store.ts
import { MerchantAPI } from '../../utils/api'
import { MerchantInfo } from '../../types/merchant'

interface StorePageData {
  hasLogin: boolean;
  loading: boolean;
  statusBarHeight: number;
  navHeight: number;
  contentPaddingTop: number;
  
  // 商家完整信息（整合个人中心的数据结构）
  merchantInfo: Partial<MerchantInfo>;
  isBusinessLicenseImage: boolean;
  isFoodLicenseImage: boolean;
  
  // 营业状态
  businessStatus: number;
  statusTexts: string[];
  autoAcceptOrder: boolean;
  
  // 配送设置
  deliverySettings: {
    minOrderAmount: number;
    deliveryFee: number;
  };
  serviceRadius: number;
  
  // 编辑表单（废弃，改用跳转到edit-profile）
  showEditModal: boolean;
  
  // 配送设置弹窗
  showDeliveryModal: boolean;
  deliveryForm: {
    minOrderAmount: string;
    deliveryFee: string;
  };
  
  // 服务范围设置弹窗
  showServiceRadiusModal: boolean;
  serviceRadiusForm: string;
  
  // 营业时间设置
  showBusinessHoursModal: boolean;
  businessHours: {
    startTime: string;
    endTime: string;
    is24Hours: boolean;
  };
}

Page({
  data: {
    hasLogin: false,
    loading: false,
    statusBarHeight: 0,
    navHeight: 0,
    contentPaddingTop: 0,
    
    // 商家完整信息
    merchantInfo: {},
    isBusinessLicenseImage: false,
    isFoodLicenseImage: false,
    
    // 营业状态
    businessStatus: 0,
    statusTexts: ['营业中', '休息中', '暂停营业'],
    autoAcceptOrder: true,
    
    // 配送设置
    deliverySettings: {
      minOrderAmount: 20.00,
      deliveryFee: 3.00
    },
    serviceRadius: 3000,
    
    // 编辑表单
    showEditModal: false,
    
    // 配送设置弹窗
    showDeliveryModal: false,
    deliveryForm: {
      minOrderAmount: '20',
      deliveryFee: '3'
    },
    
    // 服务范围设置弹窗
    showServiceRadiusModal: false,
    serviceRadiusForm: '3000',
    
    // 营业时间设置
    showBusinessHoursModal: false,
    businessHours: {
      startTime: '08:00',
      endTime: '22:00',
      is24Hours: false
    }
  } as StorePageData,

  onLoad() {
    const systemInfo = wx.getSystemInfoSync();
    const statusBarHeight = systemInfo.statusBarHeight || 0;
    const navHeight = statusBarHeight + 44;
    this.setData({
      statusBarHeight,
      navHeight,
      contentPaddingTop: navHeight + 16
    });
    
    this.checkLoginStatus();
    if (this.data.hasLogin) {
      this.loadMerchantInfo();
    }
  },

  onShow() {
    this.checkLoginStatus();
    // 每次显示页面时刷新数据
    if (this.data.hasLogin) {
      this.loadMerchantInfo();
    }
  },

  // 检查登录状态
  checkLoginStatus() {
    const token = wx.getStorageSync('merchantToken');
    const userInfo = wx.getStorageSync('merchantUserInfo');
    
    if (token && userInfo) {
      this.setData({
        hasLogin: true
      });
    } else {
      this.setData({
        hasLogin: false
      });
    }
  },

  // 返回上一页
  navigateBack() {
    wx.navigateBack({
      delta: 1
    });
  },

  // 去登录页
  goToLogin() {
    wx.navigateTo({
      url: '/pages/auth/auth'
    });
  },

  /**
   * 加载商家信息（整合个人中心的逻辑）
   */
  async loadMerchantInfo() {
    this.setData({ loading: true });
    
    try {
      // 先从缓存读取
      const cachedInfo = wx.getStorageSync('merchantUserInfo');
      if (cachedInfo) {
        const normalized = this.normalizeMerchantInfo(cachedInfo);
        const isBusinessLicenseImage = this.isImageUrl(normalized.businessLicense);
        const isFoodLicenseImage = this.isImageUrl(normalized.foodLicense);
        
        this.setData({
          merchantInfo: normalized,
          isBusinessLicenseImage,
          isFoodLicenseImage,
          businessStatus: this.getBusinessStatus(normalized)
        });
      }

      // 调用后端API获取最新信息
      const response = await MerchantAPI.getMerchantInfo();
      if (response.code === 200) {
        const merchantData = this.normalizeMerchantInfo(response.data);
        
        const isBusinessLicenseImage = this.isImageUrl(merchantData.businessLicense);
        const isFoodLicenseImage = this.isImageUrl(merchantData.foodLicense);
        
        this.setData({
          merchantInfo: merchantData,
          isBusinessLicenseImage,
          isFoodLicenseImage,
          businessStatus: this.getBusinessStatus(merchantData)
        });
        
        // 更新缓存
        wx.setStorageSync('merchantUserInfo', merchantData);
      }
    } catch (error) {
      console.error('加载商家信息失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },
  
  /**
   * 获取营业状态
   */
  getBusinessStatus(merchantInfo: any): number {
    const statusNum = typeof merchantInfo.status === 'string' ? parseInt(merchantInfo.status) : merchantInfo.status;
    return statusNum || 0;
  },

  /**
   * 归一化商家信息数据，补充前端展示所需字段
   */
  normalizeMerchantInfo(rawInfo: any) {
    if (!rawInfo) {
      return {};
    }

    const statusNum = this.getBusinessStatus(rawInfo);
    const statusText =
      rawInfo.statusText ||
      (statusNum === 0 ? '营业中' : statusNum === 1 ? '休息中' : statusNum === 2 ? '暂停营业' : '未知');

    return {
      ...rawInfo,
      status: statusNum,
      statusText,
      canOperate: rawInfo.canOperate != null ? rawInfo.canOperate : statusNum === 0,
      avatarUrl:
        rawInfo.avatarUrl ||
        rawInfo.shopAvatar ||
        rawInfo.avatar ||
        rawInfo.shopAvatarUrl ||
        ''
    };
  },
  
  /**
   * 判断是否为图片URL
   */
  isImageUrl(url?: string | null): boolean {
    if (!url || typeof url !== 'string') {
      return false;
    }
    return url.startsWith('http') || url.startsWith('/');
  },

  /**
   * 切换营业状态（整合个人中心的逻辑）- 适配switch开关
   */
  async toggleBusinessStatus(e: any) {
    const { merchantInfo } = this.data;
    
    // 检查商家是否被封禁
    const statusNum = typeof merchantInfo.status === 'string' ? parseInt(merchantInfo.status) : merchantInfo.status;
    if (statusNum === 2) {
      wx.showToast({
        title: '商家已被封禁，无法切换状态',
        icon: 'none',
        duration: 2000
      });
      // 恢复开关状态
      this.setData({
        'merchantInfo.canOperate': !e.detail.value
      });
      return;
    }

    // 检查审核状态
    if (merchantInfo.auditStatus !== 'APPROVED') {
      wx.showToast({
        title: '请先通过商家审核',
        icon: 'none',
        duration: 2000
      });
      // 恢复开关状态
      this.setData({
        'merchantInfo.canOperate': !e.detail.value
      });
      return;
    }

    // 从switch的change事件获取目标状态
    // e.detail.value: true=营业中(0), false=休息中(1)
    const targetStatus = e.detail.value ? 0 : 1;
    const targetStatusText = targetStatus === 0 ? '营业' : '休息';
    const currentStatusText = targetStatus === 0 ? '休息' : '营业';

    wx.showModal({
      title: '切换营业状态',
      content: `当前状态：${currentStatusText}\n确认切换为：${targetStatusText}？`,
      confirmText: '确认切换',
      confirmColor: '#5cb85c',
      success: async (res) => {
        if (res.confirm) {
          await this.updateBusinessStatus(targetStatus);
        } else {
          // 用户取消，恢复开关状态
          this.setData({
            'merchantInfo.canOperate': !e.detail.value
          });
        }
      },
      fail: () => {
        // 恢复开关状态
        this.setData({
          'merchantInfo.canOperate': !e.detail.value
        });
      }
    });
  },

  /**
   * 更新营业状态
   */
  async updateBusinessStatus(status: number) {
    wx.showLoading({
      title: '更新中...',
      mask: true
    });

    try {
      const response = await MerchantAPI.updateMerchantStatus(status);
      
      if (response.code === 200) {
        wx.hideLoading();
        
        const statusText = status === 0 ? '营业中' : '休息中';
        
        wx.showToast({
          title: `已切换为${statusText}`,
          icon: 'success',
          duration: 2000
        });

        // 更新本地数据
        this.setData({
          'merchantInfo.status': status,
          'merchantInfo.statusText': statusText,
          'merchantInfo.canOperate': status === 0,
          businessStatus: status
        });

        // 更新缓存
        const cachedInfo = wx.getStorageSync('merchantUserInfo') || {};
        cachedInfo.status = status;
        cachedInfo.statusText = statusText;
        cachedInfo.canOperate = status === 0;
        wx.setStorageSync('merchantUserInfo', cachedInfo);

        // 重新加载商家信息
        setTimeout(() => {
          this.loadMerchantInfo();
        }, 1000);
      } else {
        wx.hideLoading();
        wx.showToast({
          title: response.msg || '切换失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('切换营业状态失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: '切换失败，请重试',
        icon: 'none'
      });
    }
  },

  /**
   * 切换自动接单
   */
  async toggleAutoAccept(e: any) {
    const autoAccept = e.detail.value;
    
    try {
      // 调用后端API：/merchant/store/order-mode
      // await MerchantAPI.updateOrderMode({
      //   acceptOrderMode: autoAccept ? 'auto' : 'manual'
      // });
      
      this.setData({
        autoAcceptOrder: autoAccept
      });
      
      wx.showToast({
        title: autoAccept ? '自动接单已开启' : '手动接单已开启',
        icon: 'success'
      });
      
    } catch (error) {
      console.error('更新接单方式失败:', error);
      wx.showToast({
        title: '更新失败',
        icon: 'none'
      });
    }
  },

  /**
   * 编辑门店资料
   */
  editStore() {
    wx.navigateTo({
      url: '/pages/store/edit-store'
    });
  },
 
  /**
   * 选择头像（整合个人中心的逻辑）
   */
  async chooseAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: async (res) => {
        const tempFilePath = res.tempFilePaths[0];
        
        wx.showLoading({ title: '上传中...', mask: true });
        
        try {
          const uploadRes = await MerchantAPI.uploadShopAvatar(tempFilePath);
          
          if (uploadRes.code === 200) {
            const avatarUrl =
              uploadRes.data?.shopAvatar ||
              uploadRes.data?.avatarUrl ||
              uploadRes.data?.avatar ||
              uploadRes.shopAvatar ||
              uploadRes.avatarUrl ||
              uploadRes.avatar ||
              tempFilePath;
            
            console.log('头像上传成功，URL:', avatarUrl);
            
            // 立即更新界面显示
            this.setData({
              'merchantInfo.avatarUrl': avatarUrl,
              'merchantInfo.shopAvatar': avatarUrl
            });
            
            // 更新缓存中的头像信息
            const cachedInfo = wx.getStorageSync('merchantUserInfo') || {};
            cachedInfo.avatarUrl = avatarUrl;
            cachedInfo.shopAvatar = avatarUrl;
            wx.setStorageSync('merchantUserInfo', cachedInfo);
            
            wx.hideLoading();
            wx.showToast({
              title: '头像更新成功',
              icon: 'success'
            });
            
            // 重新加载商家信息
            setTimeout(() => {
              this.loadMerchantInfo();
            }, 1000);
          } else {
            wx.hideLoading();
            wx.showToast({
              title: uploadRes.msg || '上传失败',
              icon: 'none'
            });
          }
        } catch (error) {
          console.error('上传头像失败:', error);
          wx.hideLoading();
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          });
        }
      }
    });
  },

  /**
   * 预览图片
   */
  previewImage(e: any) {
    const url = e.currentTarget.dataset.url;
    if (url) {
      wx.previewImage({
        urls: [url],
        current: url
      });
    }
  },

  /**
   * 查看位置（使用腾讯地图）
   */
  async viewLocation() {
    const { merchantInfo } = this.data;
    
    if (!merchantInfo.latitude || !merchantInfo.longitude) {
      wx.showToast({
        title: '暂无位置信息',
        icon: 'none'
      });
      return;
    }

    try {
      // 导入腾讯地图工具
      const TencentMapService = require('../../utils/tencent-map').default;
      
      // 构建位置信息
      const locationInfo = {
        name: merchantInfo.merchantName || '商家位置',
        address: merchantInfo.address || '',
        latitude: Number(merchantInfo.latitude),
        longitude: Number(merchantInfo.longitude)
      };

      // 使用腾讯地图打开位置
      await TencentMapService.openLocation(locationInfo);
      
    } catch (error: any) {
      console.error('打开地图失败:', error);
      if (error.code !== 'USER_CANCEL') {
        wx.showToast({
          title: error.message || '打开地图失败',
          icon: 'none'
        });
      }
    }
  },


  /**
   * 上传背景图
   */
  uploadBackground() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        this.uploadBackgroundImage(tempFilePath);
      }
    });
  },

  /**
   * 上传背景图片到服务器
   */
  async uploadBackgroundImage(filePath: string) {
    wx.showLoading({
      title: '上传中...'
    });

    try {
      // 调用后端API：/merchant/store/upload-background
      // const response = await MerchantAPI.uploadBackground(filePath);
      
      // 模拟上传成功
      setTimeout(() => {
        this.setData({
          'storeInfo.backgroundImage': filePath
        });
        
        wx.hideLoading();
        wx.showToast({
          title: '上传成功',
          icon: 'success'
        });
      }, 1500);
      
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: '上传失败',
        icon: 'none'
      });
    }
  },

  /**
   * 预览背景图
   */
  previewBackground() {
    if (this.data.storeInfo.backgroundImage) {
      wx.previewImage({
        urls: [this.data.storeInfo.backgroundImage],
        current: this.data.storeInfo.backgroundImage
      });
    }
  },

  /**
   * 显示营业时间设置
   */
  showBusinessHoursModal() {
    this.setData({
      showBusinessHoursModal: true
    });
  },

  /**
   * 保存营业时间
   */
  async saveBusinessHours() {
    const { businessHours } = this.data;
    
    if (!businessHours.is24Hours && businessHours.startTime >= businessHours.endTime) {
      wx.showToast({
        title: '营业结束时间必须晚于开始时间',
        icon: 'none'
      });
      return;
    }

    this.setData({ loading: true });

    try {
      // 调用后端API：/merchant/store/info
      const businessHoursText = businessHours.is24Hours 
        ? '24小时营业' 
        : `${businessHours.startTime}-${businessHours.endTime}`;
        
      // await MerchantAPI.updateStoreInfo({
      //   businessHours: businessHoursText,
      //   timeRanges: businessHours.is24Hours ? [] : [{
      //     dayOfWeek: 1,
      //     startTime: businessHours.startTime,
      //     endTime: businessHours.endTime
      //   }],
      //   is24Hours: businessHours.is24Hours ? 1 : 0
      // });
      
      this.setData({
        'storeInfo.businessHours': businessHoursText,
        showBusinessHoursModal: false
      });
      
      wx.showToast({
        title: '营业时间已更新',
        icon: 'success'
      });
      
    } catch (error) {
      console.error('更新营业时间失败:', error);
      wx.showToast({
        title: '更新失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  /**
   * 显示配送设置弹窗
   */
  showDeliverySettings() {
    this.setData({
      showDeliveryModal: true,
      deliveryForm: {
        minOrderAmount: this.data.deliverySettings.minOrderAmount.toString(),
        deliveryFee: this.data.deliverySettings.deliveryFee.toString()
      }
    });
  },

  /**
   * 保存配送设置
   */
  async saveDeliverySettings() {
    const { deliveryForm } = this.data;
    
    // 验证输入
    const minOrderAmount = parseFloat(deliveryForm.minOrderAmount);
    const deliveryFee = parseFloat(deliveryForm.deliveryFee);
    
    if (isNaN(minOrderAmount) || minOrderAmount < 0) {
      wx.showToast({
        title: '请输入有效的起送价',
        icon: 'none'
      });
      return;
    }
    
    if (isNaN(deliveryFee) || deliveryFee < 0) {
      wx.showToast({
        title: '请输入有效的配送费',
        icon: 'none'
      });
      return;
    }
    
    wx.showLoading({ title: '保存中...' });

    try {
      // 调用后端API：/merchant/store/delivery-settings
      // await MerchantAPI.updateDeliverySettings({
      //   minOrderAmount: minOrderAmount,
      //   deliveryFee: deliveryFee
      // });
      
      this.setData({
        deliverySettings: {
          minOrderAmount: minOrderAmount,
          deliveryFee: deliveryFee
        },
        showDeliveryModal: false
      });
      
      wx.hideLoading();
      wx.showToast({
        title: '配送设置已更新',
        icon: 'success'
      });
      
    } catch (error) {
      wx.hideLoading();
      console.error('更新配送设置失败:', error);
      wx.showToast({
        title: '更新失败',
        icon: 'none'
      });
    }
  },

  /**
   * 显示服务范围设置弹窗
   */
  showServiceRadiusSettings() {
    this.setData({
      showServiceRadiusModal: true,
      serviceRadiusForm: this.data.serviceRadius.toString()
    });
  },

  /**
   * 保存服务范围设置
   */
  async saveServiceRadius() {
    const { serviceRadiusForm } = this.data;
    
    const radius = parseInt(serviceRadiusForm);
    
    if (isNaN(radius) || radius <= 0 || radius > 10000) {
      wx.showToast({
        title: '请输入有效范围(1-10000米)',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({ title: '保存中...' });

    try {
      // 调用后端API：/merchant/store/service-radius
      // await MerchantAPI.updateServiceRadius({
      //   serviceRadius: radius
      // });
      
      this.setData({
        serviceRadius: radius,
        showServiceRadiusModal: false
      });
      
      wx.hideLoading();
      wx.showToast({
        title: '配送范围已更新',
        icon: 'success'
      });
      
    } catch (error) {
      wx.hideLoading();
      console.error('更新配送范围失败:', error);
      wx.showToast({
        title: '更新失败',
        icon: 'none'
      });
    }
  },

  // 表单输入处理
  onStartTimeChange(e: any) {
    this.setData({
      'businessHours.startTime': e.detail.value
    });
  },

  onEndTimeChange(e: any) {
    this.setData({
      'businessHours.endTime': e.detail.value
    });
  },

  on24HoursChange(e: any) {
    this.setData({
      'businessHours.is24Hours': e.detail.value.includes('24hours')
    });
  },

  // 表单输入处理
  onMinOrderAmountInput(e: any) {
    this.setData({
      'deliveryForm.minOrderAmount': e.detail.value
    });
  },

  onDeliveryFeeInput(e: any) {
    this.setData({
      'deliveryForm.deliveryFee': e.detail.value
    });
  },

  onServiceRadiusInput(e: any) {
    this.setData({
      serviceRadiusForm: e.detail.value
    });
  },

  // 弹窗控制
  closeDeliveryModal() {
    this.setData({
      showDeliveryModal: false
    });
  },

  closeServiceRadiusModal() {
    this.setData({
      showServiceRadiusModal: false
    });
  },

  closeBusinessHoursModal() {
    this.setData({
      showBusinessHoursModal: false
    });
  },

  preventClose() {
    // 阻止事件冒泡，防止点击模态框内容时关闭
  }
});

